import React from 'react';
import { Box, Typography, Button } from '@mui/material';
import { PieChart } from '@mui/x-charts/PieChart';

const QuizResult = ({ userAnswers, quizData, onRestart }) => {
  const quizAmount = Object.keys(userAnswers).length;
  const calculateScore = () => {
    return Object.keys(userAnswers).reduce((score, key) => {
      const questionIndex = parseInt(key, 10);
      return userAnswers[key] == quizData[questionIndex]?.correctAnswerIndex ? score + 1 : score;
    }, 0);
  };
   
  const score = calculateScore();
  const data = [
    { label: '正确', value: score },
    { label: '错误', value: quizAmount - score },
  ];

  return (
    <Box sx={{ textAlign: 'center', p: 3 }}>
      <Typography variant="h5" gutterBottom>
        测验完成！您的得分：{score}/{quizAmount}
      </Typography>
      <PieChart
        series={[{ data, innerRadius: 30, outerRadius: 100, paddingAngle: 5, cornerRadius: 5 }]}
        width={300}
        height={200}
        sx={{ margin: '0 auto' }}
      />
      <Button
        variant="contained"
        color="primary"
        onClick={onRestart}
        sx={{ mt: 3 }}
      >
        再次测验
      </Button>
    </Box>
  );
};

export default QuizResult;